<template>
  <div class="questions-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>题库管理</span>
          <el-button
            v-if="userStore.isAdmin || userStore.isTeacher"
            type="primary"
            @click="handleCreate"
          >
            新增题目
          </el-button>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryForm" class="search-form" label-width="80px">
        <el-form-item label="课程">
          <el-select
            v-model="queryForm.courseId"
            placeholder="请选择课程"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="course in courseOptions"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题型">
          <el-select
            v-model="queryForm.type"
            placeholder="请选择题型"
            clearable
            style="width: 150px"
          >
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
            <el-option label="判断题" value="judge" />
            <el-option label="填空题" value="fill" />
            <el-option label="主观题" value="essay" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select
            v-model="queryForm.difficulty"
            placeholder="请选择难度"
            clearable
            style="width: 120px"
          >
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>
        <el-form-item label="题目内容">
          <el-input
            v-model="queryForm.content"
            placeholder="请输入题目内容"
            clearable
            @keyup.enter="handleQuery"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-space>
        </el-form-item>
      </el-form>
      
      <!-- 题目表格 -->
      <el-table
        v-loading="loading"
        :data="questionList"
        border
        stripe
        size="small"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="题型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="题目内容" min-width="300">
          <template #default="{ row }">
            <div class="question-content" v-html="formatContent(row.content)"></div>
          </template>
        </el-table-column>
        <el-table-column label="难度" width="100">
          <template #default="{ row }">
            <el-tag :type="getDifficultyTagType(row.difficulty)">
              {{ getDifficultyName(row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分值" width="80" />
        <el-table-column label="所属课程" width="150">
          <template #default="{ row }">
            {{ getCourseName(row.courseId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleView(row.id)"
            >
              查看
            </el-button>
            <el-button
              v-if="userStore.isAdmin || (userStore.isTeacher && canEdit(row))"
              link
              type="warning"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="userStore.isAdmin || (userStore.isTeacher && canEdit(row))"
              link
              type="danger"
              @click="handleDelete(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 题目表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="questionFormRef"
        :model="questionForm"
        :rules="questionFormRules"
        label-width="100px"
      >
        <el-form-item label="题型" prop="type">
          <el-select
            v-model="questionForm.type"
            placeholder="请选择题型"
            style="width: 100%"
            @change="handleTypeChange"
          >
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
            <el-option label="判断题" value="judge" />
            <el-option label="填空题" value="fill" />
            <el-option label="主观题" value="essay" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属课程" prop="courseId">
          <el-select
            v-model="questionForm.courseId"
            placeholder="请选择课程"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="course in courseOptions"
              :key="course.id"
              :label="course.name"
              :value="course.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-select
            v-model="questionForm.difficulty"
            placeholder="请选择难度"
            style="width: 100%"
          >
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>
        <el-form-item label="分值" prop="score">
          <el-input-number
            v-model="questionForm.score"
            :min="0"
            :max="100"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="题干" prop="content">
          <el-input
            v-model="questionForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入题目内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
        
        <!-- 选项（仅选择题显示） -->
        <el-form-item
          v-if="questionForm.type === 'single' || questionForm.type === 'multiple'"
          label="选项"
          prop="options"
        >
          <div v-for="(option, key) in questionForm.options" :key="key" class="option-item">
            <el-input
              v-model="questionForm.options[key]"
              :placeholder="`选项${key}`"
              style="width: calc(100% - 80px); margin-right: 10px"
            >
              <template #prepend>{{ key }}</template>
            </el-input>
            <el-button
              v-if="Object.keys(questionForm.options).length > 2"
              type="danger"
              @click="removeOption(key)"
            >
              删除
            </el-button>
          </div>
          <el-button
            v-if="Object.keys(questionForm.options).length < 8"
            type="primary"
            plain
            @click="addOption"
            style="margin-top: 10px"
          >
            添加选项
          </el-button>
        </el-form-item>
        
        <!-- 判断题答案 -->
        <el-form-item
          v-if="questionForm.type === 'judge'"
          label="正确答案"
          prop="answer"
        >
          <el-radio-group v-model="questionForm.answer">
            <el-radio label="true">正确</el-radio>
            <el-radio label="false">错误</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 其他题型的答案 -->
        <el-form-item
          v-else
          label="正确答案"
          prop="answer"
        >
          <el-input
            v-if="questionForm.type === 'single' || questionForm.type === 'multiple'"
            v-model="questionForm.answer"
            :placeholder="questionForm.type === 'single' ? '请输入选项字母，如：A' : '请输入选项字母，多个用逗号分隔，如：A,B,C'"
            maxlength="50"
          />
          <el-input
            v-else
            v-model="questionForm.answer"
            type="textarea"
            :rows="3"
            :placeholder="questionForm.type === 'fill' ? '请输入正确答案' : '请输入参考答案'"
            maxlength="1000"
          />
        </el-form-item>
        
        <el-form-item label="题目解析">
          <el-input
            v-model="questionForm.analysis"
            type="textarea"
            :rows="3"
            placeholder="请输入题目解析（可选）"
            maxlength="1000"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="题目详情"
      width="800px"
    >
      <el-descriptions :column="2" border v-if="viewQuestion">
        <el-descriptions-item label="ID">{{ viewQuestion.id }}</el-descriptions-item>
        <el-descriptions-item label="题型">
          <el-tag :type="getTypeTagType(viewQuestion.type)">
            {{ getTypeName(viewQuestion.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="难度">
          <el-tag :type="getDifficultyTagType(viewQuestion.difficulty)">
            {{ getDifficultyName(viewQuestion.difficulty) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="分值">{{ viewQuestion.score }}</el-descriptions-item>
        <el-descriptions-item label="所属课程" :span="2">
          {{ getCourseName(viewQuestion.courseId) }}
        </el-descriptions-item>
        <el-descriptions-item label="题干" :span="2">
          <div class="question-content" v-html="formatContent(viewQuestion.content)"></div>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="viewQuestion.options && Object.keys(viewQuestion.options).length > 0"
          label="选项"
          :span="2"
        >
          <div v-for="(value, key) in viewQuestion.options" :key="key" class="option-display">
            <strong>{{ key }}.</strong> {{ value }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="正确答案" :span="2">
          {{ viewQuestion.answer }}
        </el-descriptions-item>
        <el-descriptions-item
          v-if="viewQuestion.analysis"
          label="题目解析"
          :span="2"
        >
          {{ viewQuestion.analysis }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(viewQuestion.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(viewQuestion.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../store/user'
import { getQuestionList, createQuestion, updateQuestion, deleteQuestion, getQuestionById, type QuestionInfo } from '../../api/question'
import { getMyCourses, getCourseList } from '../../api/course'

const userStore = useUserStore()

const loading = ref(false)
const submitLoading = ref(false)
const questionList = ref<QuestionInfo[]>([])
const courseOptions = ref<any[]>([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const currentQuestionId = ref<number | null>(null)
const viewQuestion = ref<QuestionInfo | null>(null)

const queryForm = reactive({
  type: '',
  courseId: null as number | null,
  difficulty: '',
  content: ''
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const questionFormRef = ref<any>(null)
const questionForm = reactive({
  type: 'single',
  content: '',
  options: {} as Record<string, string>,
  answer: '',
  analysis: '',
  difficulty: 'medium',
  score: 5.0,
  courseId: null as number | null
})

const questionFormRules = {
  type: [
    { required: true, message: '请选择题型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入题目内容', trigger: 'blur' },
    { min: 5, max: 2000, message: '题目内容长度在5到2000个字符', trigger: 'blur' }
  ],
  answer: [
    { required: true, message: '请输入正确答案', trigger: 'blur' }
  ],
  courseId: [
    { required: true, message: '请选择所属课程', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入分值', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '分值范围0-100', trigger: 'blur' }
  ]
}

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑题目' : '新增题目'
})

// 判断是否可以编辑（教师只能编辑自己课程的题目）
const canEdit = (row: QuestionInfo) => {
  if (userStore.isAdmin) return true
  if (userStore.isTeacher) {
    // 这里可以根据创建者判断，或者根据课程权限判断
    // 简化处理：教师可以编辑自己课程的题目
    return true
  }
  return false
}

// 获取题型名称
const getTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    single: '单选题',
    multiple: '多选题',
    judge: '判断题',
    fill: '填空题',
    essay: '主观题'
  }
  return typeMap[type] || type
}

// 获取题型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    single: 'primary',
    multiple: 'success',
    judge: 'warning',
    fill: 'info',
    essay: 'danger'
  }
  return typeMap[type] || ''
}

// 获取难度名称
const getDifficultyName = (difficulty?: string) => {
  const difficultyMap: Record<string, string> = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return difficultyMap[difficulty || 'medium'] || '中等'
}

// 获取难度标签类型
const getDifficultyTagType = (difficulty?: string) => {
  const difficultyMap: Record<string, string> = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return difficultyMap[difficulty || 'medium'] || 'warning'
}

// 获取课程名称
const getCourseName = (courseId?: number) => {
  const course = courseOptions.value.find((c: any) => c.id === courseId)
  return course ? course.name : '-'
}

// 格式化内容（处理换行）
const formatContent = (content?: string) => {
  if (!content) return '-'
  return content.replace(/\n/g, '<br>')
}

// 加载课程列表
const loadCourses = async () => {
  try {
    if (userStore.isAdmin) {
      // 管理员可以查看所有课程，使用分页查询获取所有课程
      const res = await getCourseList({
        page: 1,
        size: 1000
      })
      courseOptions.value = res.data.data || []
    } else if (userStore.isTeacher) {
      // 教师只能查看自己的课程
      const res = await getMyCourses()
      courseOptions.value = res.data || []
    }
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  }
}

// 获取题目列表
const fetchQuestionList = async () => {
  loading.value = true
  try {
    const queryParams: any = {
      type: queryForm.type || undefined,
      courseId: queryForm.courseId || undefined,
      difficulty: queryForm.difficulty || undefined,
      content: queryForm.content || undefined,
      page: pagination.page,
      size: pagination.size
    }
    
    const res = await getQuestionList(queryParams)
    
    questionList.value = res.data.data || []
    pagination.total = res.data.total || 0
  } catch (error) {
    ElMessage.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  fetchQuestionList()
}

// 重置
const handleReset = () => {
  queryForm.type = ''
  queryForm.courseId = null
  queryForm.difficulty = ''
  queryForm.content = ''
  handleQuery()
}

// 分页改变
const handlePageChange = (page: number) => {
  pagination.page = page
  fetchQuestionList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchQuestionList()
}

// 新增
const handleCreate = () => {
  isEdit.value = false
  currentQuestionId.value = null
  resetQuestionForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: QuestionInfo) => {
  isEdit.value = true
  currentQuestionId.value = row.id
  Object.assign(questionForm, {
    type: row.type || 'single',
    content: row.content || '',
    options: row.options || {},
    answer: row.answer || '',
    analysis: row.analysis || '',
    difficulty: row.difficulty || 'medium',
    score: row.score || 5.0,
    courseId: row.courseId || null
  })
  
  // 如果是选择题但没有选项，初始化选项
  if ((row.type === 'single' || row.type === 'multiple') && (!row.options || Object.keys(row.options).length === 0)) {
    questionForm.options = { A: '', B: '', C: '', D: '' }
  }
  
  dialogVisible.value = true
}

// 查看
const handleView = async (id: number) => {
  try {
    const res = await getQuestionById(id)
    viewQuestion.value = res.data
    viewDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取题目详情失败')
  }
}

// 删除
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该题目吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteQuestion(id)
    ElMessage.success('删除成功')
    fetchQuestionList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 题型改变
const handleTypeChange = (type: string) => {
  if (type === 'single' || type === 'multiple') {
    // 选择题：初始化选项
    if (!questionForm.options || Object.keys(questionForm.options).length === 0) {
      questionForm.options = { A: '', B: '', C: '', D: '' }
    }
  } else {
    // 非选择题：清空选项
    questionForm.options = {}
  }
  
  // 清空答案
  questionForm.answer = ''
}

// 添加选项
const addOption = () => {
  const keys = Object.keys(questionForm.options)
  const lastKey = keys[keys.length - 1]
  const nextKey = String.fromCharCode(lastKey.charCodeAt(0) + 1)
  questionForm.options[nextKey] = ''
}

// 删除选项
const removeOption = (key: string) => {
  delete questionForm.options[key]
}

// 提交表单
const handleSubmit = async () => {
  if (!questionFormRef.value) return
  
  await questionFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    // 验证选择题选项
    if (questionForm.type === 'single' || questionForm.type === 'multiple') {
      const optionKeys = Object.keys(questionForm.options)
      if (optionKeys.length < 2) {
        ElMessage.warning('选择题至少需要2个选项')
        return
      }
      
      // 检查选项内容是否为空
      for (const key of optionKeys) {
        if (!questionForm.options[key] || questionForm.options[key].trim() === '') {
          ElMessage.warning(`选项${key}不能为空`)
          return
        }
      }
      
      // 验证答案格式
      if (questionForm.type === 'single') {
        if (!optionKeys.includes(questionForm.answer)) {
          ElMessage.warning('单选题答案必须是选项中的字母')
          return
        }
      } else if (questionForm.type === 'multiple') {
        const answerKeys = questionForm.answer.split(',').map((a: string) => a.trim())
        if (answerKeys.length < 2) {
          ElMessage.warning('多选题至少需要2个答案')
          return
        }
        for (const key of answerKeys) {
          if (!optionKeys.includes(key)) {
            ElMessage.warning(`答案${key}不在选项中`)
            return
          }
        }
      }
    }
    
    submitLoading.value = true
    
    try {
      const submitData: any = {
        type: questionForm.type,
        content: questionForm.content,
        answer: questionForm.answer,
        analysis: questionForm.analysis || undefined,
        difficulty: questionForm.difficulty,
        score: questionForm.score,
        courseId: questionForm.courseId
      }
      
      // 选择题需要提交选项
      if (questionForm.type === 'single' || questionForm.type === 'multiple') {
        submitData.options = questionForm.options
      }
      
      if (isEdit.value) {
        await updateQuestion(currentQuestionId.value!, submitData)
        ElMessage.success('更新成功')
      } else {
        await createQuestion(submitData)
        ElMessage.success('创建成功')
      }
      
      dialogVisible.value = false
      fetchQuestionList()
    } catch (error) {
      // 错误已在拦截器中处理
    } finally {
      submitLoading.value = false
    }
  })
}

// 重置表单
const resetQuestionForm = () => {
  Object.assign(questionForm, {
    type: 'single',
    content: '',
    options: { A: '', B: '', C: '', D: '' },
    answer: '',
    analysis: '',
    difficulty: 'medium',
    score: 5.0,
    courseId: null
  })
  questionFormRef.value?.clearValidate()
}

// 关闭对话框
const handleDialogClose = () => {
  resetQuestionForm()
}

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

onMounted(async () => {
  await loadCourses()
  fetchQuestionList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
  font-size: 16px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.question-content {
  max-height: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.option-display {
  margin-bottom: 8px;
  padding: 5px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>

